package com.xxgc.spring.controller;

import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @ClassName FileController
 * @Description: TODO
 * @Author 石嘉懿
 * @Date 2021/11/11
 * @Version V1.0
 **/
@Controller
@RequestMapping("/file")
public class FileController {
    //获取服务器的jquery版本
    @RequestMapping("/getJquery")
    public String getJquery(String version){
        System.out.println("version = " + version);
        //权限验证
        //放一些操作
        return "js/jquery-"+version+".js";
    }

    //获取服务器的jquery版本
    @RequestMapping("/getJquery/{version}")
    public String getJquery1(@PathVariable("version") String version){
        System.out.println("version = " + version);
        //权限验证
        //放一些操作
        return "js/jquery-"+version+".js";
    }
    @RequestMapping("/uploadFile")
    @ResponseBody
    public String uploadFile(String nickName,MultipartFile uploadImg) throws IOException {
        //保存文件
        //解决生产环境用户提交文件名重复问题
        //方案1 日期文件夹
        String yyyyMMdd = new SimpleDateFormat("yyyyMMdd").format(new Date());
        //方案2 UUID
        String uuid = UUID.randomUUID().toString().replace("-", "");
        //截取后缀
        String suffix = StringUtils.getFilenameExtension(uploadImg.getOriginalFilename());
        //文件名
        String fileName = yyyyMMdd+"\\"+uuid+"."+suffix;
        uploadImg.transferTo(new File("D:\\upload\\"+fileName));
        System.out.println("nickName = " + nickName);
        //日期+时间+地区编码+网店id+用户id+UUID的前10位
        //1 把fileName保持到数据库

        //2 把fileName返回回去
        return "\\abb\\"+fileName;
    }

    @RequestMapping("/uploadFiles")
    @ResponseBody
    public List uploadFiles(MultipartFile[] uploadImgs) throws IOException {
        List<String> strings = new ArrayList<String>();
        for (MultipartFile uploadImg : uploadImgs) {//循环文件数组
            //方案1 日期文件夹
            String yyyyMMdd = new SimpleDateFormat("yyyyMMdd").format(new Date());
            //方案2 UUID
            String uuid = UUID.randomUUID().toString().replace("-", "");
            //截取后缀
            String suffix = StringUtils.getFilenameExtension(uploadImg.getOriginalFilename());
            //文件名
            String fileName = yyyyMMdd+"\\"+uuid+"."+suffix;
            uploadImg.transferTo(new File("D:\\upload\\"+fileName));
            strings.add("\\abb\\"+fileName);
        }
        return strings;
    }
}
